<script>
import OrderListItem from "@/pagesOrders/components/OrderListItem.vue"
import {getOrderListApi} from "@/pagesOrders/api/orders"
import SafeBox from "@/components/SafeBox.vue"
import {getSafeAreaInsets} from "@/utils/safeAreaInsets"

export default {
  name: "Orders",
  components: {
    SafeBox,
    OrderListItem
  },
  data() {
    return {
      active: 'all', // 当前选中的tab栏
      page: 1, // 第几页的数据（15条一页）
      list: []
    }
  },
  onLoad(options) {
    // 接收从 My 页面传递过来的 dataType
    this.active = options.dataType || 'all'
    this.getOrderList()
  },
  methods: {
    getSafeAreaInsets,
    // 根据不同的active获取订单列表
    async getOrderList() {
      const res = await getOrderListApi(this.active, this.page)
      const list = res.data.list.data

      // 计算每个订单的商品总数，一个订单可以有不同的多个商品
      list.forEach((item) => {
        item.total_num = item.goods.reduce((sum, good) => {
          return sum + good.total_num
        }, 0)
      })

      this.list = list
    },
    onClick(event) {
      this.active = event.detail.name
    }
  },
  watch: {
    active: {
      handler() {
        this.getOrderList()
      }
    }
  }
}
</script>

<template>
  <div class="orders">
    <view class="_header">
      <van-nav-bar title="我的订单" left-arrow @click-left="uni.navigateBack"/>

      <van-tabs :active="active" @click="onClick">
        <van-tab name="all" title="全部"></van-tab>
        <van-tab name="payment" title="待支付"></van-tab>
        <van-tab name="delivery" title="待发货"></van-tab>
        <van-tab name="received" title="待收货"></van-tab>
        <van-tab name="comment" title="待评价"></van-tab>
      </van-tabs>
    </view>

    <div v-if="list.length > 0" class="content">
      <OrderListItem
          v-for="item in list"
          :key="item.order_id"
          :item="item"
          @order-updated="getOrderList"
          @click.native="uni.navigateTo({url:`/pagesOrders/pages/OrderDetail/OrderDetail?orderId=${item.order_id}`})"
      >
        <!--@click.native 相当于是在组件根元素使用原生的 click 事件，而不是使用自定义的 click 事件-->
      </OrderListItem>

      <!--如果有订单列表，那就可以显示底部，如果没有订单列表，那就不能显示底部-->
      <view class="_footer">
        亲，没有更多了
      </view>

      <SafeBox></SafeBox>
    </div>

    <div v-else class="empty" :style="{height: `calc(100vh - 90px - ${getSafeAreaInsets()})`}">
      <image src="@/static/empty.png" alt=""/>
      <div class="tips">
        亲，暂无订单记录
      </div>
    </div>

  </div>
</template>

<style lang="less">

.orders {
  background-color: #fafafa;
}

._header {
  position: sticky;
  top: 0;
  width: 100%;

  .van-tabs {
    border-bottom: 1px solid #ebedf0;
  }
}

._footer {
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: gray;
}

.empty {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  image {
    width: 140px;
    height: 92px;
  }

  .tips {
    margin: 30px 0;
    color: #666;
  }
}
</style>
